package com.hrt.manage.product.controllor;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import com.hrt.base.BaseController;
import com.hrt.bean.ProductDetails;
import com.hrt.bean.ProductInfor;
import com.hrt.bean.UserVO;
import com.hrt.bean.UsersInfor;
import com.hrt.manage.product.service.ProDetailsService;
import com.hrt.manage.product.service.ProInforService;
import com.hrt.manage.sequence.service.SequenceService;
import com.hrt.util.PageUtils;

@Controller
@RequestMapping("/manage/product/proDetails")
public class ProductDetailsController extends BaseController<ProductDetails> {

	@Autowired
	private ProDetailsService proDetailsService;

	@Autowired
	private ProInforService proInforService;

	private ProductDetails detail;
	
	@Autowired
	private SequenceService sequenceService;

	protected ProductInfor product;

	public ProductInfor getProduct() {
		return product;
	}

	public void setProduct(ProductInfor product) {
		this.product = product;
	}

	@RequestMapping(value = "/list")
	public ModelAndView list(
			@RequestParam(value = "id", required = true) Long proId,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView();
		if(proId!=null){
		List list = new ArrayList();
		product=proInforService.getProductByid(proId);
	

		list = proDetailsService.queryByProId(proId, getPageIndex(),
				getPageSize());
		setTotalCount(proDetailsService.totalCount(proId));
		this.setList(list);
		this.setPageCount(this.computePageCount(this.getTotalCount(),
				this.getPageSize()));

		page = this.getPage();
		// view.addObject("proTypes", getProTypes());
		view.addObject("proId", proId);
		view.addObject("pageResult", page);
		}else{
			// error handle..
		}
		return view;
	}

	@RequestMapping(value = "/queryByPage")
	@ResponseBody
	public Map<String, PageUtils<ProductDetails>> queryByPage(
			@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
			@RequestParam(value = "pageSize", required = false) Integer pageSize,
			@RequestParam(value = "id", required = true) Long proId,
			HttpServletRequest request) {
		Map<String, PageUtils<ProductDetails>> resultMap = new HashMap<String, PageUtils<ProductDetails>>();

		if (pageSize == null || "".equals(pageSize)) {
			pageSize = 30;
		}
		if (pageIndex == null || "".equals(pageIndex)) {
			pageIndex = 1;
		}
		setPageIndex(pageIndex);

		setPageSize(pageSize);
		List<ProductDetails> resultList = new ArrayList();
		setTotalCount(proDetailsService.totalCount(proId));
		if (proId == null) {
			throw new RuntimeException("产品编号有误");
		} else {
			product=proInforService.getProductByid(proId);
			resultList = proDetailsService.queryByProId(proId, pageIndex,
					pageSize);
		}
		setList(resultList);

		this.setPageCount(this.computePageCount(this.getTotalCount(),
				this.getPageSize()));

		page = this.getPage();

		resultMap.put("pageResult", page);
		return resultMap;
	}

	@RequestMapping(value = "/show")
	@ResponseBody
	public Map show(@RequestParam(value = "id", required = true) Long deId,
			HttpServletRequest request, HttpServletResponse response) {

		Map map = new HashMap();
		if (deId != null && !"".equals(deId)) {
			// Map resultMap=new HashMap<K, V>();
			System.out.println("showshowshowshowshow " + deId);
			detail = this.proDetailsService.getDetailById(deId);
			if (detail != null) {
				map = transBean2Map(detail);
//				for (Iterator<Map.Entry> itr = map.entrySet().iterator(); itr
//						.hasNext();) {
//					Map.Entry entry = itr.next();
//					System.out.println(entry.getKey().toString());
//					System.out.println(entry.getValue().toString());
//				}
			}

		}
		return map;

	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public void save(@ModelAttribute("protypeDetail") ProductDetails detail,
			HttpServletRequest request, HttpServletResponse response) {

		System.out.println("save");
		System.out.println(product.getId());
		System.out.println(product.getProCode());
		System.out.println(product.getProName());
		System.out.println(product.getDescription());
		if (product != null) {

			try {

				UserVO user = this.getOnlineManager(request, response);
				detail.setProductInfor(product);
				detail.setCreateId(user.getUserId());
				detail.setCreator(user.getLoinName());
				detail.setCreatTime(new java.sql.Date(new java.util.Date()
						.getTime()));
				detail.setEditor(detail.getCreator());
				detail.setEditorId(detail.getCreateId());
				detail.setEditTime(new java.sql.Date(new java.util.Date()
						.getTime()));

				this.proDetailsService.saveDetail(detail);
				proInforService.updateTotal(product);
				response.sendRedirect("list.do?id=" + product.getId());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public void update(@ModelAttribute("protypeDetail") ProductDetails pro,
			HttpServletRequest request, HttpServletResponse response) {
		System.out.println("update");
		System.out.println(detail.getProCode());
		System.out.println(detail.getProName());
		System.out.println(detail.getId());
		System.out.println(detail.getDescription());

		try {
			UserVO user = this.getOnlineManager(request, response);
			this.detail.setProCode(pro.getProCode());
			this.detail.setProName(pro.getProName());
			this.detail.setEnterPrice(pro.getEnterPrice());
			this.detail.setSalePrice(pro.getSalePrice());
			this.detail.setHeight(pro.getHeight());
			this.detail.setWidth(pro.getWidth());
			this.detail.setLongness(pro.getLongness());
			this.detail.setDescription(pro.getDescription());
			this.detail.setEditorId(user.getUserId());
			this.detail.setColor(pro.getColor());
			this.detail.setEditor(user.getLoinName());
			this.detail.setTotal(pro.getTotal());
			this.detail.setEditTime(new java.sql.Date(new java.util.Date()
					.getTime()));
			this.proDetailsService.udateDetail(this.detail);
		//	proInforService.updateTotal(detail.getProductInfor());
			response.sendRedirect("list.do?id=" + detail.getProId());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody Long[] delete(
			@RequestParam(value = "ids", required = true) String ids,
			HttpServletResponse response) throws IOException {
		Long[] idArr = null;
		ModelAndView view = new ModelAndView();

		if (ids != null) {
			if (ids.indexOf(",") != -1) {
				String[] idStrs = ids.split(",");
				idArr = new Long[idStrs.length];
				for (int idx = 0; idx < idStrs.length; idx++) {
					idArr[idx] = Long.parseLong(idStrs[idx]);
				}
			} else {
				idArr = new Long[] { Long.parseLong(ids) };
			}

		}
		try {
			proDetailsService.deleteById(idArr);
			//proInforService.updateTotal(product);
			return idArr;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

	}

	@RequestMapping(value = "/add")
	@ResponseBody
	public Map<String, Object> add(
			@RequestParam(value = "id", required = true) Long proId,
			HttpServletRequest request) {
		if (proId != null && !"".equals(proId)) {
			product = proInforService.getProductByid(proId);
		}
		detail = getDetail();
		String proCode=product.getProCode();
		detail.setProCode(proCode);
		String seqNum=sequenceService.getNextSequence(ProductDetails.class);
		seqNum=proCode+"_"+seqNum;
		detail.setRuleCode(seqNum);
		detail.setProName(product.getProName());
		detail.setProductInfor(product);

		Map<String, Object> map = BaseController.transBean2Map(detail);

		return map;

	}

	public ProductDetails getDetail() {
		
			detail = new ProductDetails();
	
		return detail;
	}

	public void setDetail(ProductDetails detail) {
		this.detail = detail;
	}

}
